package com.jieyang.oa.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 29276
 * @version 1.0
 * @description: TODO
 * @date 2021/8/21 20:47
 */
@WebFilter("/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求的URI地址
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        HttpServletResponse resp=(HttpServletResponse)servletResponse;
        String requestURI = req.getRequestURI();
//        System.out.println(requestURI);
        //硬性放行
        if( requestURI.endsWith("login.jsp") ||
                requestURI.endsWith(".js")       ||
                requestURI.endsWith(".css")      ||
                requestURI.contains("images")    ||
                requestURI.endsWith("codeServlet") ||
                requestURI.endsWith("codeCheckServlet") ||
                requestURI.endsWith("userServlet") ||
                requestURI.contains("main")      ||
                requestURI.endsWith("favicon.ico") ||
                requestURI.endsWith("emailCode.jsp") ||
                requestURI.endsWith("forgetPwdServlet") ||
                requestURI.endsWith("forgetPwd.jsp") ||
                requestURI.endsWith("myInfServlet")
        ){
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            //session校验
            HttpSession session = req.getSession();
            session.setMaxInactiveInterval(3600*24);
            Object emp = session.getAttribute("emp");
            if(emp != null){
                //放行
                filterChain.doFilter(servletRequest,servletResponse);
            }else{
                //判断请求是否为Ajax请求
                if(req.getHeader("x-requested-with") != null && req.getHeader("x-requested-with").equals("XMLHttpRequest") ){
                    resp.getWriter().write("sessionTimeOut");
                }else{
                    //重定向到登录页面
                    resp.sendRedirect(req.getContextPath()+"/login.jsp");
                }

            }
        }
    }

    @Override
    public void destroy() {

    }
}

